package com.spring.framework.aop.aspect;

import org.aspectj.weaver.tools.PointcutExpression;
import org.aspectj.weaver.tools.PointcutParser;
import org.aspectj.weaver.tools.ShadowMatch;

import java.lang.reflect.Method;

/***
 * 解析Aspect表达式及定位被织入的目标
 */
public class AspectJExpressionPointcut {

	/**
	 * PointCut解析器
	 */
	private PointcutParser pointcutParser = PointcutParser.getPointcutParserSupportingSpecifiedPrimitivesAndUsingSpecifiedClassLoaderForResolution(
			PointcutParser.getAllSupportedPointcutPrimitives(), this.getClass().getClassLoader()
	);


	/**
	 * 表达式解析器
	 */
	private PointcutExpression pointcutExpression;

	/**
	 * 根据表达式解析
	 *
	 * @param expression
	 */
	public AspectJExpressionPointcut(String expression) {
		this.pointcutExpression = pointcutParser.parsePointcutExpression(expression);
	}


	/**
	 * 判断传入的Class是否符合切点表达式匹配——初筛
	 *
	 * @param targetClass
	 * @return
	 */
	public boolean rougthMatches(Class<?> targetClass) {
		return pointcutExpression.couldMatchJoinPointsInType(targetClass);
	}

	/**
	 * 判断传入的Class是否符合切点表达式匹配——精筛
	 *
	 * @param method
	 * @return
	 */
	public boolean accurateMatches(Method method) {
		ShadowMatch shadowMatch = pointcutExpression.matchesMethodExecution(method);
		return shadowMatch.alwaysMatches();
	}
}
